import logging

from myapp.models.model_user import MyUser
from myapp.third.auth.config import CASDOOR_APP, CASDOOR_ORG
from myapp.third.auth.db import casdoor_session_scope
from myapp.utils.sess import session_scope
from myapp.utils.strings import is_valid_email, is_valid_phone_number

logger = logging.getLogger(__name__)


def sync_user():
    skip_users = []
    while True:
        with session_scope(nullpool=True) as sess:
            q = sess.query(MyUser).filter_by(taichu='')
            if len(skip_users) > 0:
                q = q.filter(MyUser.username.notin_(skip_users))

            usr = q.first()
            if usr is None:
                logger.info('exit sync_user')

                return

            # 检查casdoor是否已经存在该用户
            u = sdk.get_user(usr.username)
            if u:
                logger.error(f'{usr.username} 已存在')
                skip_users.append(usr.username)
                continue

            password = usr.password
            password_type = 'pbkdf2-salt'
            salt = ''
            if password.startswith('pbkdf2:sha256:'):
                _, salt, hash_val = password.split('$')
                password = hash_val
            else:
                logger.info(f'{usr.username} 密码为plain')
                password_type = 'plain'

            # 检查手机号是否合法
            phone = usr.phone
            if not is_valid_phone_number(phone):
                logger.info(f'[{usr.username}] 非法的手机号 {phone}')
                phone = ''

            email = usr.email
            if not is_valid_email(email):
                logger.info(f'[{usr.username}] 非法的邮箱 {email}')
                email = ''

            created_time = usr.created_on.strftime('%Y-%m-%dT%H:%M:%SZ')
            updated_time = usr.changed_on.strftime('%Y-%m-%dT%H:%M:%SZ')

            with casdoor_session_scope() as casdoor_sess:
                casdoor_sess.execute(
                    'INSERT INTO casdoor.user (owner, name, created_time, updated_time,'
                    ' deleted_time, id, external_id, type, password, password_salt,'
                    ' password_type, display_name, first_name, last_name, avatar, avatar_type,'
                    ' permanent_avatar, email, email_verified, phone, country_code, region,'
                    ' location, address, affiliation, title, id_card_type, id_card, homepage,'
                    ' bio, tag, language, gender, birthday, education, score, karma, ranking,'
                    ' is_default_avatar, is_online, is_admin, is_forbidden, is_deleted,'
                    ' signup_application, hash, pre_hash, access_key, access_secret, created_ip,'
                    ' last_signin_time, last_signin_ip, github, google, qq, wechat, facebook,'
                    ' dingtalk, weibo, gitee, linkedin, wecom, lark, gitlab, adfs, baidu, alipay,'
                    ' casdoor, infoflow, apple, azuread, azureadb2c, slack, steam, bilibili,'
                    ' okta, douyin, line, amazon, auth0, battlenet, bitbucket, box, cloudfoundry,'
                    ' dailymotion, deezer, digitalocean, discord, dropbox, eveonline, fitbit,'
                    ' gitea, heroku, influxcloud, instagram, intercom, kakao, lastfm, mailru,'
                    ' meetup, microsoftonline, naver, nextcloud, onedrive, oura, patreon, paypal,'
                    ' salesforce, shopify, soundcloud, spotify, strava, stripe, tiktok, tumblr,'
                    ' twitch, twitter, typetalk, uber, vk, wepay, xero, yahoo, yammer, yandex,'
                    ' zoom, metamask, web3onboard, custom, webauthnCredentials,'
                    ' preferred_mfa_type, recovery_codes, totp_secret, mfa_phone_enabled,'
                    ' mfa_email_enabled, invitation, invitation_code, ldap, properties, roles,'
                    ' permissions, `groups`, last_signin_wrong_time, signin_wrong_times,'
                    f" managedAccounts) VALUES ('{CASDOOR_ORG}', '{usr.username}',"
                    f" '{created_time}', '{updated_time}', '', '{usr.id}', '',"
                    f" 'normal-user', '{password}', '{salt}', '{password_type}', '',"
                    f" '', '', '', '', '', '{email}', 0, '{phone}', '', '',"
                    " '', '[]', '', '', '', '', '', '', '', '', '', '',"
                    f" '', 0, 0, 1, 0, 0, 0, 0, 0, '{CASDOOR_APP}', '', '', '', '',"
                    " '', '', '', '', '', '', '', '', '', '', '', '',"
                    " '', '', '', '', '', '', '', '', '', '', '', '',"
                    " '', '', '', '', '', '', '', '', '', '', '', '',"
                    " '', '', '', '', '', '', '', '', '', '', '', '',"
                    " '', '', '', '', '', '', '', '', '', '', '', '',"
                    " '', '', '', '', '', '', '', '', '', '', '', '',"
                    " '', '', '', '', '', '', '', '', 0x6E756C6C, '', 'null',"
                    " '', 0, 0, '', '', '', 'null', 'null', 'null', 'null', '',"
                    ' 0, 0x6E756C6C)'
                )

            new_user = sdk.get_user(usr.username)
            logger.info(f'新用户 已创建{new_user.id}')
            usr.taichu = str(new_user.id)
